package com.jrx.anytxn.customer.mq;

import com.jrx.anytxn.common.exception.TxnBadGatewayException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.customer.bean.CustomerInfoBean;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.constant.ErrorMsgConstant;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.TlDelaySms;
import com.jrx.anytxn.customer.mapper.base.TlDelaySmsMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.service.IDealCustGatewayService;
import com.jrx.anytxn.feign.api.request.UserInfoUpdateRequest;
import com.jrx.anytxn.feign.api.service.IUserApiService;
import com.jrx.anytxn.feign.common.GateWayPredicate;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.feign.gateway.bean.DocumentInfo;
import com.jrx.anytxn.feign.gateway.response.EcifResponse02;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.entity.PrChannelTable;
import com.jrx.anytxn.param.entity.PrSmsTemplateTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrChannelTableMapper;
import com.jrx.anytxn.param.service.sms.ISmsTemplatesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liuyu
 * @Description
 */
@Service
@RocketMQMessageListener(
        topic = CustomerConstant.MQ_ID_INVALID_TOPIC + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumerGroup = CustomerConstant.MQ_ID_INVALID_GROUP + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumeThreadMax = 10
)
public class BatchIdInvalidMqConsumerService implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(BatchIdInvalidMqConsumerService.class);

    @Autowired
    private IInnerGatewayService iInnerGatewayService;
    @Autowired
    private IDealCustGatewayService dealCustGatewayService;
    @Resource
    private ExtCmCustomerSecondLevelMapper extCmCustomerSecondLevelMapper;
    @Resource
    private ExtPrChannelTableMapper extPrChannelTableMapper;
    @Resource
    private TlDelaySmsMapper tlDelaySmsMapper;
    @Autowired
    private ISegmentService iSegmentService;
    @Autowired
    private IUserApiService iUserApiService;
    @Resource
    private ExtCmCustomerFirstLevelMapper extCmCustomerFirstLevelMapper;
    @Autowired
    private ISmsTemplatesService smsTemplatesService;

    @Override
    public void onMessage(String s) {

        logger.info("接受到的mq消息：{}", s);
        CustomerInfoBean bean;
        EcifResponse02 queryResult = null;
        try {
            bean = JsonUtils.json2pojo(s, CustomerInfoBean.class);

            // 获取自营渠道
            List<PrChannelTable> prChannelTables =
                    extPrChannelTableMapper.selectAllByTenIdAndPrivateChannel(bean.getModifyCmCustomerFirstLevel().getTenantId(), CustomerConstant.PRIVATE_CHANNEL_YES);

            // 构建查询的ECIF客户信息
            String ecifRequest02Json = dealCustGatewayService.buildQueryEcifReq(bean);
            // 查询
            GateWayPredicate<EcifResponse02> queryPred = () -> iInnerGatewayService.queryEcifInfo(ecifRequest02Json);
            queryResult = queryPred.getRes(queryPred);
            // 未查询到
            if (null == queryResult) {
                logger.info("未查询到exif客户信息，客户id：{}", bean.getModifyCmCustomerFirstLevel().getCustomerId());
                this.sendSMS(prChannelTables, bean);
                return;
            }

            List<DocumentInfo> documentInfoList = queryResult.getPrtDocumentArray();
            if (null == documentInfoList || documentInfoList.isEmpty()) {
                logger.debug("身份信息未查询到, ecif客户号：{}", queryResult.getEcifNo());
                this.sendSMS(prChannelTables, bean);
                return;
            }
            //获取身份证证件信息
            DocumentInfo documentInfo = documentInfoList.stream().filter(d -> "0".equals(d.getGoveIdenNumTypeCode())).findFirst().get();
            // ecif证件失效日期大于txn证件失效日期，更新客户一级信息表中的生效和失效日期
            if (documentInfo.getExpiryDate().compareTo(bean.getModifyCmCustomerFirstLevel().getIdExpireDate()) <= 0) {
                logger.info("ecif客户号{}：ecif证件失效日期小于等于txn证件失效日期，ecif失效日期{}，txn失效日期{}", documentInfo.getCertNo(), documentInfo.getExpiryDate(), bean.getModifyCmCustomerFirstLevel().getIdExpireDate());
                this.sendSMS(prChannelTables, bean);
            }

            if (documentInfo.getExpiryDate().compareTo(bean.getModifyCmCustomerFirstLevel().getIdExpireDate()) > 0) {
                logger.info("ecif客户号{}：ecif证件失效日期大于txn证件失效日期，ecif失效日期{}，txn失效日期{}", documentInfo.getCertNo(), documentInfo.getExpiryDate(), bean.getModifyCmCustomerFirstLevel().getIdExpireDate());
                bean.getModifyCmCustomerFirstLevel().setIdExpireDate(documentInfo.getExpiryDate());
                bean.getModifyCmCustomerFirstLevel().setIdEffectiveDate(documentInfo.getEffectDate());
                CmCustomerFirstLevel updateFirst = new CmCustomerFirstLevel();
                updateFirst.setId(bean.getModifyCmCustomerFirstLevel().getId());
                updateFirst.setCustomerId(bean.getModifyCmCustomerFirstLevel().getCustomerId());
                updateFirst.setTenantId(bean.getModifyCmCustomerFirstLevel().getTenantId());
                updateFirst.setIdEffectiveDate(documentInfo.getEffectDate());
                updateFirst.setIdExpireDate(documentInfo.getExpiryDate());
                extCmCustomerFirstLevelMapper.updateByIdAndCustomerIdAndTenantId(updateFirst);
                // 通知api同步更新客户信息
                UserInfoUpdateRequest request = new UserInfoUpdateRequest();
                request.setTenantId(bean.getModifyCmCustomerFirstLevel().getTenantId());
                // 查询客户二级档，获取渠道为自营（渠道配置）的二级档信息，如果没有自营渠道二级档，则不处理
                CmCustomerSecondLevel cmCustomerSecondLevel = null;
                for (PrChannelTable channelTable : prChannelTables) {
                    cmCustomerSecondLevel =
                            extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(bean.getModifyCmCustomerFirstLevel().getCustomerId(), channelTable.getChannelId(), bean.getModifyCmCustomerFirstLevel().getTenantId());
                    if (cmCustomerSecondLevel != null) {
                        break;
                    }

                }

                if (null == cmCustomerSecondLevel) {
                    return;
                }
                request.setUserId(cmCustomerSecondLevel.getUserId());
                request.setChannelNo(cmCustomerSecondLevel.getChannel());
                request.setReqId(CustomerConstant.GATEWAY_SERVICE_ID);
                request.setName(bean.getModifyCmCustomerFirstLevel().getChineseName());
                request.setCertNo(bean.getModifyCmCustomerFirstLevel().getIdNumber());
                request.setIssuedBy(bean.getModifyCmCustomerFirstLevel().getIdIssueAgent());
                request.setIdExpireDate(DateUtils.parseStringDate(documentInfo.getExpiryDate(), DateUtils.DATE_PATTERN, DateUtils.DATE_PATTERN_ANOTHER));
                request.setIdEffectiveDate(DateUtils.parseStringDate(documentInfo.getEffectDate(), DateUtils.DATE_PATTERN, DateUtils.DATE_PATTERN_ANOTHER));
                String toJSon = JsonUtils.toJSon(request);
                ApiResponse<UserInfoUpdateRequest> response = iUserApiService.updateCustomerInfo(toJSon);
                if (response == null || response.getCode() != 1000) {
                    throw new TxnBadGatewayException(ErrorMsgConstant.GATEWAY_ERROR);
                }
            }

        } catch (Exception e) {
            logger.error("解析异常", e);
        }

    }

    private void sendSMS(List<PrChannelTable> prChannelTables, CustomerInfoBean bean) throws Exception {
        logger.info("短信发送，客户id为：{}", bean.getModifyCmCustomerFirstLevel().getCustomerId());
        if (CollectionUtils.isEmpty(prChannelTables)) {
            return;
        }
        // 查询客户二级档，获取渠道为自营（渠道配置）的二级档信息，如果没有自营渠道二级档，则不处理
        CmCustomerSecondLevel cmCustomerSecondLevel = null;
        for (PrChannelTable channelTable : prChannelTables) {
            cmCustomerSecondLevel =
                    extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(bean.getModifyCmCustomerFirstLevel().getCustomerId(), channelTable.getChannelId(), bean.getModifyCmCustomerFirstLevel().getTenantId());
            if (cmCustomerSecondLevel != null) {
                break;
            }
        }

        if (null == cmCustomerSecondLevel) {
            return;
        }
        // 根据二级档的手机号，保存延迟短信记录表 tl_delay_sms
        CmCustomerFirstLevel firstLevel = bean.getModifyCmCustomerFirstLevel();
        TlDelaySms tlDelaySms = new TlDelaySms();
        tlDelaySms.setId(iSegmentService.getId(CustomerConstant.TL_DELAY_SMS_ID));
        tlDelaySms.setTenantId(firstLevel.getTenantId());
        tlDelaySms.setOrganizationId(firstLevel.getOrganizationId());
        tlDelaySms.setCustomerId(firstLevel.getCustomerId());
        tlDelaySms.setMobile(cmCustomerSecondLevel.getMobile());
        tlDelaySms.setChannel(cmCustomerSecondLevel.getChannel());
        tlDelaySms.setSmsType(CustomerConstant.DELAY_SYS_TYPE);
        PrSmsTemplateTable templateTable = smsTemplatesService.selectByTenantIdAndTemplateId(firstLevel.getTenantId(), CustomerConstant.DELAY_SMS_TEMPLATE_ID);
        ;
        smsTemplatesService.selectByTenantIdAndTemplateId(firstLevel.getTenantId(), CustomerConstant.DELAY_SMS_TEMPLATE_ID);
        if (null == templateTable) {
            return;
        }
        tlDelaySms.setTemplateId(CustomerConstant.DELAY_SMS_TEMPLATE_ID);
        tlDelaySms.setDealStatus(CustomerConstant.DELAY_SMS_DEAL_STATUS);
        tlDelaySms.setBusinessDate(firstLevel.getNextProcessingDate());
        tlDelaySms.setUpdateBy(CustomerConstant.DELAY_SMS_UPDATE_BY);
        tlDelaySms.setRecordVersionNumber(1);
        tlDelaySmsMapper.insertSelective(tlDelaySms);
    }
}
